package com.zjt.pictureselector.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.zjt.pictureselector.holder.FolderHolder;
import com.zjt.pictureselector.model.FolderBean;
import com.zjt.pictureselector.model.MediaBean;

import java.io.File;
import java.util.List;

public class FolderAdapter extends RecyclerView.Adapter<FolderHolder> {

    private Context mContext;
    private List<FolderBean> mFolders;
    private int mSelectItem;
    private OnFolderSelectListener mListener;

    public FolderAdapter(Context context, List<FolderBean> folders) {
        mContext = context;
        mFolders = folders;
    }

    @Override
    public FolderHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new FolderHolder(LayoutInflater.from(mContext), parent);
    }

    @Override
    public void onBindViewHolder(final FolderHolder holder,int position) {
        final FolderBean folder = mFolders.get(position);
        List<MediaBean> mediaBeanList = folder.getMediaBeanList();
        holder.getTvFolderName().setText(folder.getFolderName());
        holder.getIvSelect().setVisibility(mSelectItem == position ? View.VISIBLE : View.GONE);
        if (mediaBeanList != null && !mediaBeanList.isEmpty()) {
            holder.getTvFolderSize().setText(mediaBeanList.size() + "张");
            Glide.with(mContext)
                    .load(new File(mediaBeanList.get(0).getPath()))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(holder.getIvImage());
        } else {
            holder.getTvFolderSize().setText("0张");
            holder.getIvImage().setImageBitmap(null);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectItem = holder.getAdapterPosition();
                notifyDataSetChanged();
                if(mListener != null){
                    mListener.OnFolderSelect(folder);
                }
            }
        });
    }

    public void refresh(List<FolderBean> folders){
        mFolders = folders;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mFolders == null ? 0 : mFolders.size();
    }

    public void setOnFolderSelectListener(OnFolderSelectListener listener) {
        this.mListener = listener;
    }

    public interface OnFolderSelectListener {
        void OnFolderSelect(FolderBean folder);
    }

}
